package top.kaoshanji.r3ch12a;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 代码清单-r4ch12a-393页b：在没有事务环境下操作数据库是可以的
 * @author kaoshanji
 * ^_^
 * create time 2025/5/9 17:17
 */
public class UserJdbcWithoutTransManagerServiceContext {

    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("r3ch12a/jdbcWithoutTx.xml");

        UserJdbcWithoutTransManagerService service = (UserJdbcWithoutTransManagerService)context.getBean("userService");
        JdbcTemplate jdbcTemplate = (JdbcTemplate)context.getBean("jdbcTemplate");

        BasicDataSource dataSource = (BasicDataSource)jdbcTemplate.getDataSource();

        // 检查数据源autoCommit的设置
        System.out.println("数据源事务默认设置：" + dataSource.getDefaultAutoCommit());

        // 插入一条记录，初始分为 10
        jdbcTemplate.execute(" INSERT INTO t_user1(user_name,password,score,last_logon_time) VALUES('tom','123456',10, "+System.currentTimeMillis()+") ");

        // 调用工作在无事务环境下的服务类方法，将分数添加20分
        service.addScore("tom", 20);

        // 查询此时用户的分数
        int score = jdbcTemplate.queryForObject(" SELECT score FROM t_user1 WHERE user_name ='tom' ", Integer.class);
        System.out.println("积分：" + score);

        jdbcTemplate.execute(" DELETE FROM t_user1 WHERE user_name='tom' ");
    }

}
